import React, {createContext,useContext, useEffect } from 'react';
//import ReactDOM from 'react-dom/client';
import { createRoot ,Root} from 'react-dom/client';

import {message} from 'antd';
import MicorAppContext from './context/micro-app-context';
import App from './app';
import microData from './store/micro-data';
import './index.css';


let registerGlobalNum = 0;

// 定义一个新的类型，包含 Window 和自定义属性
type WindowWithCustomVars = Window & {
    __POWERED_BY_QIANKUN__: {
        onGlobalStateChange:(params:((state:any)=>void))=>void,
        setGlobalState:(params:any)=>void
    };
};
  
// 声明 window 为新的类型
declare let window: WindowWithCustomVars;

let rooter:Root;

function render(props:any) {
    const { container,onGlobalStateChange, setGlobalState} = props;
    
    onGlobalStateChange && onGlobalStateChange((state:any)=>{
        if(registerGlobalNum === 0){
            if(state.from === 'mainApp'){
                //console.log(`子应用接收到主应用传过来的数据：${JSON.stringify(state)}`);
                microData.updateMicroServiceData(state);
            }
            registerGlobalNum +=1;
        }
    });

    createRoot(container ? container.querySelector('#sub-one-root') : document.querySelector('#sub-one-root')).render(
        <MicorAppContext.Provider value={{onGlobalStateChange, setGlobalState}}>
            <App />
        </MicorAppContext.Provider>
    );
}


if (!window.__POWERED_BY_QIANKUN__) {
    render({});
}


export async function bootstrap() {

    //@ts-ignore
    __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
    //@ts-ignore
    //@ts-ignore
    console.log(`window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ = ${window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__}`);

    //@ts-ignore
    console.log(`__webpack_public_path__ = ${__webpack_public_path__}`);
    console.log('[react18] react app bootstraped');
}

export async function mount(props:any) {
    render(props);
}

export async function unmount(props:any) {
    const { container } = props;

    // 获取当前的 React 根实例
    //const root = createRoot(container);

    // 卸载 React 应用
    //root.unmount();

    console.log('子应用已卸载');
}